<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;

/**
 * BOM物料清单管理
 *
 * @icon fa fa-sitemap
 * @remark 管理产品物料清单，支持多层级BOM结构
 */
class Bom extends Backend
{
    /**
     * Bom模型对象
     * @var \app\admin\model\scanwork\Bom
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\Bom;
        $this->view->assign("bomTypeList", $this->model->getBomTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['product', 'model', 'creator'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                
                // 生成BOM编号
                if (empty($params['bom_no'])) {
                    $params['bom_no'] = \app\admin\model\scanwork\Bom::generateBomNo();
                }
                
                // 设置创建人
                $params['creator_id'] = $this->auth->id;
                $params['creator_name'] = $this->auth->username;
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取产品列表
        $productList = \app\admin\model\scanwork\Product::where('status', 1)
            ->column('name', 'id');
        $this->view->assign('productList', $productList);
        
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取产品列表
        $productList = \app\admin\model\scanwork\Product::where('status', 1)
            ->column('name', 'id');
        $this->view->assign('productList', $productList);
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * BOM明细管理
     */
    public function items($ids = null)
    {
        $bom = $this->model->get($ids);
        if (!$bom) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isAjax()) {
            $items = \app\admin\model\scanwork\BomItem::where('bom_id', $ids)
                ->with(['material', 'supplier'])
                ->order('level', 'asc')
                ->order('sequence', 'asc')
                ->select();

            return json(['code' => 1, 'msg' => '', 'data' => $items]);
        }

        // 获取物料列表
        $materialList = \app\admin\model\scanwork\Material::where('status', 'active')
            ->column('material_name', 'id');
        $this->view->assign('materialList', $materialList);
        
        // 获取供应商列表
        $supplierList = \app\admin\model\scanwork\Supplier::where('status', 'active')
            ->column('supplier_name', 'id');
        $this->view->assign('supplierList', $supplierList);

        $this->view->assign('bom', $bom);
        return $this->view->fetch();
    }

    /**
     * 添加BOM明细
     */
    public function addItem()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            
            Db::startTrans();
            try {
                $bomItem = new \app\admin\model\scanwork\BomItem;
                $bomItem->save($params);
                
                // 自动计算实际用量和总价
                $bomItem->autoCalculate();
                
                Db::commit();
                $this->success('添加成功');
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
    }

    /**
     * 更新BOM明细
     */
    public function updateItem()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $id = $params['id'] ?? 0;
            
            Db::startTrans();
            try {
                $bomItem = \app\admin\model\scanwork\BomItem::get($id);
                if (!$bomItem) {
                    throw new Exception('BOM明细不存在');
                }
                
                $bomItem->save($params);
                
                // 自动计算实际用量和总价
                $bomItem->autoCalculate();
                
                Db::commit();
                $this->success('更新成功');
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
    }

    /**
     * 删除BOM明细
     */
    public function deleteItem()
    {
        $id = $this->request->post('id');
        
        Db::startTrans();
        try {
            $bomItem = \app\admin\model\scanwork\BomItem::get($id);
            if (!$bomItem) {
                throw new Exception('BOM明细不存在');
            }
            
            $bomItem->delete();
            
            Db::commit();
            $this->success('删除成功');
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 批量导入BOM明细
     */
    public function import()
    {
        return parent::import();
    }

    /**
     * 复制BOM
     */
    public function copy($ids = null)
    {
        $bom = $this->model->get($ids);
        if (!$bom) {
            $this->error(__('No Results were found'));
        }

        Db::startTrans();
        try {
            $newVersion = $this->request->post('new_version');
            $newBom = $bom->copyBom($newVersion);
            
            Db::commit();
            $this->success('复制成功', null, ['id' => $newBom->id]);
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 审核BOM
     */
    public function approve($ids = null)
    {
        $bom = $this->model->get($ids);
        if (!$bom) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $approve = $this->request->post('approve', 1);
            $remark = $this->request->post('remark', '');

            Db::startTrans();
            try {
                if ($approve == 1) {
                    $bom->status = 2; // 已发布
                    $bom->approver_id = $this->auth->id;
                    $bom->approver_name = $this->auth->username;
                    $bom->approve_time = time();
                    $bom->publish_time = time();
                } else {
                    $bom->status = 0; // 退回草稿
                }
                $bom->save();

                Db::commit();
                $this->success($approve == 1 ? '审核通过' : '已退回');
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $this->view->assign('bom', $bom);
        return $this->view->fetch();
    }

    /**
     * 获取BOM树形结构
     */
    public function tree($ids = null)
    {
        $bom = $this->model->get($ids);
        if (!$bom) {
            $this->error(__('No Results were found'));
        }

        $tree = $bom->getBomTree();
        
        return json(['code' => 1, 'msg' => '', 'data' => $tree]);
    }

    /**
     * 计算BOM成本
     */
    public function calculateCost($ids = null)
    {
        $bom = $this->model->get($ids);
        if (!$bom) {
            $this->error(__('No Results were found'));
        }

        $totalCost = $bom->calculateCost();
        
        return json(['code' => 1, 'msg' => '', 'cost' => $totalCost]);
    }
}

